package org.jeecgframework.web.system.controller.core;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.extend.datasource.DataSourceContextHolder;
import org.jeecgframework.core.extend.datasource.DataSourceType;
import org.jeecgframework.core.util.*;
import org.jeecgframework.web.service.WxCommonService;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.system.manager.ClientManager;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.MutiLangServiceI;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.adobe.xmp.impl.Base64;

@Scope("prototype")
@Controller
@RequestMapping("/loginWxController")
public class LoginWxController {

    @Autowired
    private WxCommonService wxCommonService;
    @Autowired
    private SystemService systemService;

    @Autowired
    private MutiLangServiceI mutiLangService;

    @Autowired
    private ZyCommonService zyCommonService;

    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    /**
     * 跳转到用户绑定
     *
     * @param type 1.增值产品   2.个人中心 3.保修期查询 4.快速报修
     * @return
     */
    @RequestMapping(params = "loginRedirect")
    public ModelAndView loginRedirect(HttpServletRequest request, HttpServletResponse response, String type) throws Exception {


        System.out.println("用户绑定");
        //开发模式
//        String developmentModel=ResourceUtil.getConfigByName("developmentModel");


        String sessionOpenId = (String) request.getParameter("openId");
//        sessionOpenId ="oacqX1XUgi_YdMy75LvdYUveLBD0";//测试用
//        if("local".equals(developmentModel)){
//            sessionOpenId ="oacqX1XUgi_YdMy75LvdYUveLBD0";  //银牌（已认证）
////            sessionOpenId ="o38HawiMRXzjDqdojh9SOpSg60Hs";       //金牌
////            sessionOpenId ="o38Hawrr80kCTFfczRg9JVs";       //未认证
////            sessionOpenId ="o38Hawrr80kCTFfczRg9JVsqxdEU";   //钻石
//        }

        request.getSession().setAttribute("openId", sessionOpenId);
        request.getSession().setAttribute("lang", "zh-cn");
        if ("3".equals(type)) {
            return new ModelAndView("redirect:/wxMenuController.do?selfService");
        }
        if ("9".equals(type)) {
            //扫码跳转到用户验证页面
            String serviceId = request.getParameter("serviceId");
//        String timeStr=new Date().getTime()+"";
            String timeStr = request.getParameter("qrdate");
            //两小时的毫秒值
            long fiveMin = 2 * 60 * 60 * 1000;
            Date nowTime = new Date();
            try {
                if (StringUtil.isNotEmpty(timeStr)) {
                    long createTime = Long.valueOf(timeStr);
                    long diff = nowTime.getTime() - createTime;
                    if (diff <= fiveMin) {
                        //如果二维码创建时间没有超过两小时
                        if (StringUtil.isNotEmpty(serviceId)) {
                            request.setAttribute("serviceId", serviceId);
                            return new ModelAndView("com/wx/wx_user_verifyPhone");
                        }
                    } else {
                        //如果二维码创建时间超过两小时
                        return new ModelAndView("com/wx/wx_errCode_overTime");
                    }
                }
            } catch (Exception e) {

            }
            return null;
        }

        //String auth = request.getParameter("auth");
        String auth = request.getParameter("userinfo");

//        if("local".equals(developmentModel)){
//            auth ="";
//        }

        //微信用户授权认证取的当前微信用户信息
        if (StringUtil.isEmpty(sessionOpenId) && StringUtil.isEmpty(auth)) {
            try {
                String url = URLEncoder.encode(StaticValue.HTTP_HEADER + "loginWxController.do?loginRedirect&type=" + type);

                String wxPageAuthorizeUrl = StaticValue.WX_PAGE_AUTHORIZE + "?key=" + StaticValue.WX_INPUT_KEY + "&scope=snsapi_userinfo&backurl=" + url;

                response.sendRedirect(wxPageAuthorizeUrl);
                return null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        DataSourceContextHolder.setDataSourceType(DataSourceType.dataSource_jeecg);
        if (StringUtil.isNotEmpty(auth)) {
//            String wxUserInfo = new String(PasswordUtil.decodeBase64(auth));
            String wxUserInfo = new String(Base64.decode(auth));
            System.out.println("wxUserInfo:" + wxUserInfo);
            JSONObject json = JSONObject.fromObject(wxUserInfo);
            System.out.println("json:" + json);
            sessionOpenId = json.getString("openid");
            System.out.println("sessionOpenId" + sessionOpenId);
            String headImg = json.getString("headimgurl").replace("\\", "");
            String name = json.getString("nickname");
            request.getSession().setAttribute("openId", sessionOpenId);
            request.getSession().setAttribute("headImg", headImg);
            request.getSession().setAttribute("name", name);
        }
        List<TSUser> userList = systemService.findHql("from TSUser where openId = ?", sessionOpenId);
        request.setAttribute("openId", sessionOpenId);
        System.out.println("sessionOpenId--" + sessionOpenId);
        if (userList.size() > 0) {
            System.out.println("获取到用户");
            TSUser user = userList.get(0);
            ZyContactsEntity contact = systemService.findUniqueByProperty(ZyContactsEntity.class, "tsBaseUser.id", user.getId());
            //用户表被停用  或者  联系人表离职
            if (user.getStatus().equals(Globals.User_Forbidden) || (StringUtil.isNotEmpty(contact) && StaticValue.DIC_ENGINEER_STATE_QUIT.equals(contact.getState()))) {
                try {
                    response.setHeader("Content-type", "text/html;charset=UTF-8");
                    response.setHeader("viewport", "width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no");
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().write("<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no\" />");
                    response.getWriter().write("<center>您的帐号已被停用</center>");
                    return null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            String headImg = (String) request.getSession().getAttribute("headImg");
            if (StringUtil.isNotEmpty(headImg) && !headImg.equals(user.getWxHeadImgUrl())) {
                user.setWxHeadImgUrl(headImg);
                systemService.saveOrUpdate(user);
            }
            List<TSUserOrg> departOrgList = systemService.findHql("from TSUserOrg where tsUser.id = ?", user.getId());
            message = mutiLangService.getLang("common.user") + ": " + user.getUserName();
            if (departOrgList.size() > 0) {
                TSDepart currentDepart = departOrgList.get(0).getTsDepart();
                user.setCurrentDepart(currentDepart);
                message += "[" + currentDepart.getDepartname() + "]" + mutiLangService.getLang("common.login.success");
            }
            login(request, user);
            // 添加登陆日志
            systemService.addLog(message, Globals.Log_Type_LOGIN, Globals.Log_Leavel_INFO);
            request.setAttribute("user", user);
            List<CbsWxUserBindEntity> bindList = systemService.findHql("from CbsWxUserBindEntity where userName = ? and approvalStatus =2", user.getUserName());
            request.setAttribute("isBind", bindList.size() > 0);
            if ("1".equals(type)) {//增值产品
                return new ModelAndView("com/wx/added_product/wx_menu");
            } else if ("2".equals(type)) {//个人中心
                request.setAttribute("contacts", contact);
                return new ModelAndView("com/wx/personal_center/wx_index");
            } else if ("3".equals(type)) {//自助服务
                getRepairListData(request);
                return new ModelAndView("com/wx/repair_query/wx_repair_list");
            } else if ("4".equals(type)) {//快速报修
                request.setAttribute("ct", contact);
                getQuickRepairEsData(request);
                String belongCmName = "";
                if (user.getAuthenticationLevel() != null && user.getAuthenticationLevel().equals("2")) {//钻石（原金牌）用户
                    List<CbsWxUserBindEntity> wubs = wxCommonService.findByProperty(CbsWxUserBindEntity.class, "openId", user.getOpenId());
                    if (wubs != null && wubs.size() > 0) {
                        belongCmName = wubs.get(0).getCinemaName();
                        request.setAttribute("cinemaChain", wubs.get(0).getChainName());
                    }
                } else {
                    if (contact != null) {
//                    String belongCmName = contact.getBelongCinema().getName();
                        belongCmName = contact.getCinemaName();
                    }
                }
                request.setAttribute("belongCmName", belongCmName);
                return new ModelAndView("com/wx/repair_query/quick_repair");
            } else if ("5".equals(type)) {//我的服务单
                return new ModelAndView("redirect:/loginWxController.do?goPersionalCenterServiceMenu");
            } else if ("6".equals(type)) {//我的设备
                response.sendRedirect("cbsWxUserCenterController.do?userEquipList");
            } else if ("7".equals(type)) {//巡检查询
                return new ModelAndView("redirect:/CbsWxInspectionController.do?goWxInspectionList");
            } else if ("8".equals(type)) {//申请钻石认证
                return new ModelAndView("redirect:/loginWxController.do?goVipExplain");
            }
        } else {
            System.out.println("未获取到用户");
            request.setAttribute("isBind", false);
            if ("1".equals(type)) {//增值产品
                return new ModelAndView("com/wx/added_product/wx_menu");
            }
            if ("7".equals(type)) {//巡检查询
                return new ModelAndView("redirect:/CbsWxInspectionController.do?goWxInspectionList");
            }


//            return new ModelAndView("redirect:/loginWxController.do?goUserCreate");
            //需要跳到微信端的用户注册界面
            String url = StaticValue.WX_PAGE_REGISTER;
            response.sendRedirect(url);
        }
        return null;
    }

    //我的服务单-巡检服务单-出保设备快速报修
    public void getQuickRepairEsData(HttpServletRequest request) {
        String esId = request.getParameter("esId");
        if (StringUtil.isNotEmpty(esId)) {
            ZyEquipmentSpareEntity es = systemService.getEntity(ZyEquipmentSpareEntity.class, esId);
            if (es != null) {
                request.setAttribute("sn", es.getSn());
                request.setAttribute("esTypeDesc", es.getType().getTypeDesc());
            }
        }
    }

    /**
     * 用户登录
     *
     * @param request
     * @param user
     */
    public void login(HttpServletRequest request, TSUser user) {
        Client client = new Client();
        client.setIp(IpUtil.getIpAddr(request));
        client.setLogindatetime(new Date());
        client.setUser(user);

        HttpSession session = ContextHolderUtils.getSession();
        session.setAttribute("c_user_id", user.getId());

        ClientManager.getInstance().addClinet(request.getSession().getId(), client);
    }

    /**
     * 跳转到微信注册
     */
    @RequestMapping(params = "goUserCreate")
    public ModelAndView goUserCreate(HttpServletRequest request) {
        return new ModelAndView("com/wx/wx_user_create");
    }

    /**
     * 微信注册   - 发送手机验证码
     */
    @RequestMapping(params = "sendWxPhoneCode")
    @ResponseBody
    public AjaxJson sendWxPhoneCode(HttpServletRequest request, String phoneNumber) {
        AjaxJson json = new AjaxJson();
        json.setMsg("发送成功");
        HttpSession session = request.getSession();
        String sessionId = session.getId();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("liveTime", StaticValue.SEND_RANDOMCODE_LIVETIME);
        String openId = (String) session.getAttribute("openId");
        List<TSUser> userList = systemService.findHql("from TSUser where openId = ?", openId);
        if (userList.size() > 0) {
            json.setSuccess(false);
            json.setMsg("您已经注册过帐号，请重新登录");
            return json;
        }
        json = zyCommonService.sendRandomCode(sessionId, phoneNumber, StaticValue.SEND_RANDOMCODE_LIVETIME, "sms_wx_create.ftl", map, StaticValue.RANDOMCODE_WX_CREATE);
        return json;
    }

    /**
     * 用户注册 - 验证手机验证码 并且自动创建联系人  and 用户
     */
    @RequestMapping(params = "validWxPhoneCode")
    @ResponseBody
    public AjaxJson validWxPhoneCode(String phoneCode, String realName, String phoneNumber, HttpServletRequest request) {
        AjaxJson json = new AjaxJson();
        try {
            HttpSession session = request.getSession();
            String openId = (String) session.getAttribute("openId");
            String headImg = (String) session.getAttribute("headImg");
            List<TSUser> validUserList = systemService.findHql("from TSUser where openId = ?", openId);
            if (validUserList.size() > 0) {
                json.setSuccess(false);
                json.setMsg("您已经注册过帐号，请重新登录");
                if (validUserList.get(0).getStatus().equals(Globals.User_Forbidden)) {
                    json.setMsg("您的帐号已被停用");
                }
                return json;
            }

//            List<CbsVerificationCodeEntity> codeList = systemService.findHql("from CbsVerificationCodeEntity where sessionId = ? order by createDate desc", session.getId());
//			if(codeList.size() > 0){
//				long dif = (DataUtils.getDate().getTime() - codeList.get(0).getCreateDate().getTime()) / 1000 ;
//				if(dif <= codeList.get(0).getTime() && codeList.get(0).getRandcode().equals(phoneCode)){

            List<TSUser> userList = systemService.findHql("from TSUser where mobilePhone = ?", phoneNumber);
            List<ZyContactsEntity> contactsList = systemService.findHql("from ZyContactsEntity where cellphone1 = ?", phoneNumber);

            TSUser user = null;
            ZyContactsEntity contacts = null;

            if (userList.size() > 0) {
                user = userList.get(0);
                user.setOpenId(openId);
                if ("0".equals(user.getAuthenticationLevel())) {
                    user.setAuthenticationLevel("1");
                }
                user.setWxHeadImgUrl(headImg);
                systemService.saveOrUpdate(user);
            } else {
                if (contactsList.size() > 0 && StringUtil.isNotEmpty(contactsList.get(0).getTsBaseUser())) {
                    user = systemService.get(TSUser.class, contactsList.get(0).getTsBaseUser().getId());
                } else {
                    user = new TSUser();
                }

                String userName = PinyinUtil.getPinYin(realName);
                user.setRealName(realName);
                List<TSUser> repeatUserList = systemService.findHql("from TSUser where userName = ?", userName);
                if (repeatUserList.size() > 0) {
                    Integer num = repeatUserList.size() == 1 ? 1 : repeatUserList.size() + 1;
                    userName = userName + num;
                }
                user.setUserName(userName);
                user.setPassword(PasswordUtil.encrypt(user.getUserName(), "123456", PasswordUtil.getStaticSalt()));
                user.setAppPassword(user.getPassword());
                user.setStatus(Globals.User_Normal);
                user.setActivitiSync((short) 0);
                user.setOpenId(openId);
                user.setAuthenticationLevel("1");
                user.setMobilePhone(phoneNumber);
                user.setUserKey("");
                user.setWxHeadImgUrl(headImg);
                systemService.save(user);

                TSRole role = systemService.findUniqueByProperty(TSRole.class, "roleCode", "wxrole");
                if (role != null) {
                    TSRoleUser rUser = new TSRoleUser();
                    rUser.setTSUser(user);
                    rUser.setTSRole(role);
                    systemService.save(rUser);
                }
            }
            if (contactsList.size() > 0) {
                contacts = contactsList.get(0);
                contacts.setTsBaseUser(user);
                /*更新联系人表中真是姓名*/
                contacts.setName(realName);
                systemService.saveOrUpdate(contacts);
            } else {
                contacts = new ZyContactsEntity();
                contacts.setType(StaticValue.DIC_CONTACT_TYPE_CINEMA_CONTACT);
                contacts.setName(realName);
                contacts.setCellphone1(phoneNumber);
                contacts.setSource("微信注册");
                contacts.setIsDelete("0");
                contacts.setTsBaseUser(user);
                systemService.save(contacts);
            }
            login(request, user);
            json.setMsg("验证通过");
            return json;
//				}
//			}
        } catch (Exception e) {
            e.printStackTrace();
        }
        json.setSuccess(false);
        json.setMsg("验证码错误");
        return json;
    }

    @RequestMapping(params = "goVipExplain")
    public ModelAndView goVipExplain(HttpServletRequest request) {
        return new ModelAndView("com/wx/wx_user_create_bind_explain");

    }

    @RequestMapping(params = "goVipExplainWithCancel")
    public ModelAndView goVipExplainWithCancel(HttpServletRequest request) {
        return new ModelAndView("com/wx/wx_bind_explain");

    }

    /**
     * 跳转到微信认证
     */
    @RequestMapping(params = "goUserBind")
    public ModelAndView goUserBind(HttpServletRequest request) {
        TSUser user = genUser(request);
//        TSUser user = ResourceUtil.getSessionUserName();
        String openId = "";
        if (user != null && StringUtil.isNotEmpty(user.getOpenId())) {
            openId = user.getOpenId();
        }
        List<TSTerritory> territoryList = systemService.findHql("from TSTerritory where territoryLevel = 1 order by territorySort");
        request.setAttribute("territoryList", territoryList);
        request.setAttribute("user", user);
        List<CbsWxUserBindEntity> bindList = systemService.findHql("from CbsWxUserBindEntity where openId = ?  and approvalStatus!=2 order by createDate desc", openId);
        if (bindList.size() > 0) {
            request.setAttribute("bindUserInfo", bindList.get(0));
            return new ModelAndView("redirect:/loginWxController.do?goAuthInfo");
        }
        return new ModelAndView("com/wx/wx_user_create_bind");
    }

    /**
     * 跳转到用户详情
     *
     * @return
     */
    @RequestMapping(params = "goUserInfo")
    public ModelAndView goUserInfo(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("com/wx/wx_user_info");
        TSUser user = ResourceUtil.getSessionUserName();
        ZyContactsEntity contact = systemService.findUniqueByProperty(ZyContactsEntity.class, "tsBaseUser.id", user.getId());
        request.setAttribute("contact", contact);
        request.setAttribute("user", user);
        /*来源于我的会员认证*/
        List<CbsWxUserBindEntity> wxUserList = systemService.findHql("from CbsWxUserBindEntity where userName = ?  and approvalStatus!=2 order by createDate desc", user.getUserName());
        if (wxUserList.size() > 0) {
            CbsWxUserBindEntity bindUser = wxUserList.get(0);
            mv.addObject("userInfo", bindUser);
            TSType type = zyCommonService.queryTsType(StaticValue.DIC_BUSINESS_WAY, wxUserList.get(0).getMarketingType());
            if (StringUtil.isNotEmpty(type)) {
                request.setAttribute("type", type.getTypename());
            }
            TSType userDepart = zyCommonService.queryTsType(StaticValue.DIC_CONTACT_POSITION, contact.getPosition());
            if (StringUtil.isNotEmpty(userDepart)) {
                request.setAttribute("departName", userDepart.getTypename());
            }
        }
        return mv;
    }

    @RequestMapping(params = "logOff")
    @ResponseBody
    public AjaxJson logOff(String id) {
        AjaxJson result = new AjaxJson();
        TSUser baseUser = systemService.get(TSUser.class, oConvertUtils.getString(id));
        if (baseUser == null) {
            result.setSuccess(false);
            result.setMsg("用户不存在");
        } else {
            /*设置银牌*/
            baseUser.setAppPassword("2");
            systemService.saveOrUpdate(baseUser);
        }
        return result;
    }

    @RequestMapping(params = "goAuthInfo")
    public ModelAndView goAuthInfo() {
        ModelAndView mv = new ModelAndView("redirect:/loginWxController.do?goUserBind");
        TSUser user = ResourceUtil.getSessionUserName();
        ZyContactsEntity contact = null;
        if(StringUtil.isNotEmpty(user)){
            contact = systemService.findUniqueByProperty(ZyContactsEntity.class, "tsBaseUser.id", user.getId());
            mv.addObject("contact", contact);
            mv.addObject("user", user);
        }else{
            mv.addObject("contact", "");
            mv.addObject("user", "");
        }
        /*来源于我的会员认证*/
        List<CbsWxUserBindEntity> wxUserList = systemService.findHql("from CbsWxUserBindEntity where userName = ?  and approvalStatus!=2 order by createDate desc", user.getUserName());
        if (wxUserList.size() > 0) {
            CbsWxUserBindEntity bindUser = wxUserList.get(0);
            mv.addObject("userInfo", bindUser);
            switch (bindUser.getApprovalStatus()) {
                case "0"://待审批
                    mv.setViewName("com/wx/wx_user_0_info");
                    break;
                case "1"://认证通过的用户
                    mv.setViewName("com/wx/wx_user_1_info");
                    break;
            }
            TSType type = zyCommonService.queryTsType(StaticValue.DIC_BUSINESS_WAY, wxUserList.get(0).getMarketingType());
            if (StringUtil.isNotEmpty(type)) {
                mv.addObject("type", type.getTypename());
            }
            if(StringUtil.isNotEmpty(contact)){
                TSType userDepart = zyCommonService.queryTsType(StaticValue.DIC_CONTACT_POSITION, contact.getPosition());
                if (StringUtil.isNotEmpty(userDepart)) {
                    mv.addObject("departName", userDepart.getTypename());
                }
            }else{
                mv.addObject("departName", "");
            }

        }
        return mv;
    }

    @RequestMapping(params = "goAfterBind")
    public String goAfterBind() {
        return "com/wx/wx_bind_after_submit";
    }


    /**
     * 根据选择的省查询市
     *
     * @param id 所选省
     * @return
     */
    @RequestMapping(params = "getTerritoryCity")
    @ResponseBody
    public List<TSTerritory> getTerritoryCity(String id) {
        return systemService.findHql("from TSTerritory where TSTerritory.id = ? and territoryLevel = 2 order by territorySort", id);
    }


    public void sendAuthFile(String toEmail) {
        if (!StringUtil.isEmpty(toEmail)) {
            String path = SendMailUtil.getAppPath(LoginWxController.class);
            path = path + File.separator + "jeecg" + File.separator + "template" + File.separator + "影院认证账号授权书.docx";
            File toSendFile = new File(path);
            if (toSendFile.exists()) {
                SendMailUtil.sendHTMLeMailWithAttach(toEmail, "影院认证账号授权书", new File(path));
            }
        }
    }

    /**
     * 用户认证提交
     *
     * @param request
     * @param userBindInfo
     * @return
     */
    @RequestMapping(params = "userBindSubmit")
    @ResponseBody
    public AjaxJson userBindSubmit(HttpServletRequest request, CbsWxUserBindEntity userBindInfo) {
        AjaxJson j = new AjaxJson();
        message = "用户认证提交成功";
        try {
            String openId = (String) request.getSession().getAttribute("openId");
            List<CbsWxUserBindEntity> bindList = systemService.findHql("from CbsWxUserBindEntity where openId = ? and approvalStatus = 1", openId);
            if (bindList.size() > 0) {
                j.setMsg("提交失败，您已经提交过认证");
                return j;
            }
            TSUser user = ResourceUtil.getSessionUserName();
            user = systemService.get(TSUser.class, user.getId());
//            user.setAuthenticationLevel("3");
            systemService.saveOrUpdate(user);
            userBindInfo.setOpenId(openId);
            userBindInfo.setApprovalStatus("0");
            ZyContactsEntity contacts = systemService.findUniqueByProperty(ZyContactsEntity.class, "tsBaseUser.id", user.getId());
            contacts.setEmail(userBindInfo.getEmail());
            contacts.setPosition(userBindInfo.getDepartName());
            systemService.saveOrUpdate(userBindInfo);
            if (!StringUtil.isEmpty(userBindInfo.getEmail())) {
                /*发送影院认证账号授权书*/
                sendAuthFile(userBindInfo.getEmail());
                /*发送微信提醒*/
//                Map<String, Object> map = new HashMap<String, Object>();
//                Map<String, Object> farstMap = new HashMap<String, Object>();
//                Map<String, Object> keyword1 = new HashMap<String, Object>();
//                Map<String, Object> keyword2 = new HashMap<String, Object>();
//                Map<String, Object> remarkMap = new HashMap<String, Object>();
//                StringBuilder msgContent = new StringBuilder(userBindInfo.getCreateName());
//                msgContent.append("，")
//                        .append("您好。影院认证账号授权书已发送到您的邮箱，请注意查收。");
//                farstMap.put("value", "影院认证账号授权书");
//                keyword1.put("value",  msgContent.toString());
//                keyword2.put("value", DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
//                remarkMap.put("value", "");
//                map.put("first", farstMap);
//                map.put("keyword1", keyword1);
//                map.put("keyword2", keyword2);
//                map.put("remark", remarkMap);
//                sendWxMessage.sendWxMsg(openId, StaticValue.SEND_WX_MSG_ACTION_SUCCESS_TEMPID, map);
                //调用微信接口发送
                List<Map<String, String>> list = new ArrayList<>();
                String content = "尊敬的客户，您好：影院认证账号授权书已发送到您的邮箱，请注意查收。【中影巴可客服部】";
                Map<String, String> map = new HashMap<>();
                map.put("openid", openId);
                map.put("message", content);
                list.add(map);
                wxCommonService.sendMsgForWx(list);
            }


        } catch (Exception e) {
            e.printStackTrace();
            message = "用户认证提交失败";
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 跳转到个人中心的我的服务单
     *
     * @return
     */
    @RequestMapping(params = "goPersionalCenterServiceMenu")
    public ModelAndView goPersionalCenterServiceMenu(HttpServletRequest request) {
        String openId = oConvertUtils.getString(request.getSession().getAttribute("openId"));
        System.out.println("menuopenId--" + openId);
        if (ResourceUtil.getSessionUserName() == null && StringUtil.isNotEmpty(openId)) {
            List<TSUser> users = systemService.findHql("from TSUser where openId=?", openId);
            if (users.size() > 0) {
                login(request, users.get(0));
            }
        }
        TSUser user = ResourceUtil.getSessionUserName();
        request.setAttribute("user", user);
        return new ModelAndView("com/wx/personal_center/wx_menu");
    }

    /**
     * 加载保修期查询数据
     *
     * @param request
     */
    public List<ZyEquipmentSpareEntity> getRepairListData(HttpServletRequest request) {
        String sn = request.getParameter("sn");
        List<ZyEquipmentSpareEntity> esList = systemService.findHql("from ZyEquipmentSpareEntity where isSpare = false and sn = ?", sn);
        request.setAttribute("equip", esList);
        request.setAttribute("sn", sn);
        Map<String, Object> map = new HashMap<String, Object>();
        for (int i = 0; i < esList.size(); i++) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(esList.get(i).getRepairEndDate());
            Calendar date = Calendar.getInstance();
            date.setTime(new Date());
            map.put(esList.get(i).getId(), DateUtils.dateDiff('d', cal, date));
        }
        request.setAttribute("map", map);
        return esList;
    }

    @RequestMapping(params = "downAuthInfo")
    @ResponseBody
    public AjaxJson downAuthInfo() {
        AjaxJson result = new AjaxJson();
        TSUser user = ResourceUtil.getSessionUserName();
        if (null != user && StringUtil.isNotEmpty(user.getEmail())) {
            sendAuthFile(user.getEmail());
        }
        return result;
    }


    /**
     * 跳转到扫码后输入手机号验证
     */
    @RequestMapping(params = "goUserCheck")
    public ModelAndView goUserCheck(HttpServletRequest request) {
        String serviceId = request.getParameter("serviceId");
//        String timeStr="2018-06-05 08:00:00";
        String timeStr = request.getParameter("qrdate");
        //两小时
        long fiveMin = 2 * 60 * 60 * 1000;
        Date nowTime = new Date();
        try {
            if (StringUtil.isNotEmpty(timeStr)) {
                long createTime = Long.valueOf(timeStr);
                long diff = nowTime.getTime() - createTime;
                if (diff <= fiveMin) {
                    //如果二维码创建时间没有两小时
                    if (StringUtil.isNotEmpty(serviceId)) {
                        request.setAttribute("serviceId", serviceId);
                        return new ModelAndView("com/wx/wx_user_verifyPhone");
                    }
                } else {
                    //如果二维码创建时间两小时
                    return new ModelAndView("com/wx/wx_errCode_overTime");
                }
            }
        } catch (Exception e) {

        }
        return null;
    }


    /**
     * 微信扫码跳转到手机验证页面   - 发送手机验证码
     */
    @RequestMapping(params = "sendWxCellphoneCode")
    @ResponseBody
    public AjaxJson sendWxCellphoneCode(HttpServletRequest request, String phoneNumber) {
        AjaxJson json = new AjaxJson();
        json.setMsg("发送成功");
        HttpSession session = request.getSession();
        String sessionId = session.getId();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("liveTime", StaticValue.SEND_RANDOMCODE_LIVETIME);
        List<TSUser> userList = systemService.findHql("from TSUser where mobilePhone = ?", phoneNumber);
        if (userList != null && userList.size() > 0) {
            if (StringUtil.isNotEmpty(userList.get(0).getAuthenticationLevel())) {
                if (userList.get(0).getAuthenticationLevel().equals("4")) {
                    json.setSuccess(false);
                    json.setMsg("您已成为金牌用户，感谢您的支持");
                    return json;
                }
                if (userList.get(0).getAuthenticationLevel().equals("2")) {
                    json.setSuccess(false);
                    json.setMsg("您已经是钻石用户不能验证成为金牌");
                    return json;
                }
                if (userList.get(0).getAuthenticationLevel().equals("1")) {
                    json = zyCommonService.sendRandomCode(sessionId, phoneNumber, StaticValue.SEND_RANDOMCODE_LIVETIME, "sms_wx_create.ftl", map, StaticValue.RANDOMCODE_WX_CHECK);
                }
            }
        } else {
            json.setSuccess(false);
            json.setMsg("您还未注册过会员，请注册后再验证！");
            return json;
        }

        return json;
    }


    /**
     * 用户身份验证 - 验证手机验证码 并根据身份提升为金牌
     */
    @RequestMapping(params = "validWxCellphoneCode")
    @ResponseBody
    public AjaxJson validWxCellphoneCode(String phoneCode, String phoneNumber, String serviceId, HttpServletRequest request) {
        AjaxJson json = new AjaxJson();
        try {
//            HttpSession session = request.getSession();
//            List<CbsVerificationCodeEntity> codeList = systemService.findHql("from CbsVerificationCodeEntity where sessionId = ? order by createDate desc", session.getId());
//            if (codeList.size() > 0) {
//                long dif = (DataUtils.getDate().getTime() - codeList.get(0).getCreateDate().getTime()) / 1000;
//                if (dif <= codeList.get(0).getTime() && codeList.get(0).getRandcode().equals(phoneCode)) {
            List<TSUser> goldUserList = systemService.findHql("from TSUser where serviceId = ?", serviceId);
            if (goldUserList.size() < 2) {
                List<TSUser> userList = systemService.findHql("from TSUser where mobilePhone = ?", phoneNumber);
                if (userList != null && userList.size() > 0) {
                    TSUser user = userList.get(0);
                    if (user != null && StringUtil.isNotEmpty(user.getAuthenticationLevel()) && user.getAuthenticationLevel().equals("1")) {
                        user.setAuthenticationLevel("4");
                        user.setServiceId(serviceId);
                        systemService.saveOrUpdate(user);                     
                        //调用微信接口，升级微信用户为金牌
                        String jsonString = wxCommonService.noticeAddLevel(user.getOpenId(), "PROMOTE_GOLD");
                        System.out.println("jsonString:" + jsonString);
                        json.setMsg("您已成为金牌用户，感谢您的支持");
                       // add 20190423 联系人所属影院更新 start
                        List<ZyContactsEntity> cts = systemService.findByProperty(ZyContactsEntity.class,"tsBaseUser.id",user.getId());
                        if(cts!=null && cts.size() > 0 && cts.get(0).getBelongCinema() == null){
                        	 ZyContactsEntity contacts=  cts.get(0);
                             List<CbsServiceEntity> cbsServiceList = systemService.findHql("from CbsServiceEntity where id='" + serviceId + "'");
                             if(cbsServiceList!=null && cbsServiceList.size()>0){
                            	 ZyCinemaEntity cinema =  cbsServiceList.get(0).getZyCinemaId();
	                             if(cinema!=null ){
	                            	 contacts.setBelongCinema(cinema);
	                            	 systemService.saveOrUpdate(contacts);
	                             }
                             }
                        }
                        // add 20190423 联系人所属影院更新 end
                    } else if (user != null && StringUtil.isNotEmpty(user.getAuthenticationLevel()) && user.getAuthenticationLevel().equals("4")) {
                    	//如果已经是金牌
                    	json.setMsg("您已成为金牌用户，感谢您的支持");
                    } else if (user != null && StringUtil.isNotEmpty(user.getAuthenticationLevel()) && user.getAuthenticationLevel().equals("2")) {
                    	//如果已经是钻石
                        json.setMsg("您已为钻石用户，感谢您的支持");
                    } else {
                    	json.setMsg("请您先关注【巴可数字电影易服务】并注册成为会员");
                    }
                    return json;
                } else {
                    json.setMsg("请您先关注【巴可数字电影易服务】并注册成为会员");
                    return json;
                }

            } else {
                json.setSuccess(false);
                json.setMsg("该服务单的金牌名额已满");
                return json;
            }
//                }
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        json.setSuccess(false);
        json.setMsg("验证码错误");
        return json;
    }


    public TSUser genUser(HttpServletRequest request) {
        TSUser u = ResourceUtil.getSessionUserName();
        if (null == u) {
            String openId = oConvertUtils.getString(request.getSession().getAttribute("openId"));
            u = zyCommonService.findUniqueByProperty(TSUser.class, "openId", openId);
        }
        return u;
    }
}
